package com.deva.bletest;

import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class FileSelectActivity extends Activity {

	private String mCurPath;
	private ListView mListView;
	
	private ArrayList<String> list;
	private ArrayList<String> paths;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flielist);
		
		final Intent intent = getIntent();
		mCurPath=intent.getStringExtra("CurrentPath");

		mListView = (ListView)findViewById(R.id.fileListView);
		renderFileDir(mCurPath);
		mListView.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				String path=paths.get(position);
				File file=new File(path);
				if(file.isDirectory())
				{
					renderFileDir(path);
				}
				else
				{
					mCurPath=paths.get(position);
					Intent intent=new Intent();
					intent.putExtra("CurrentPath", mCurPath);
					setResult(1,intent);
					finish();
				}
			}

		});
	}

	private void renderFileDir(String filePath) {
		// TODO Auto-generated method stub
		list = new ArrayList<String>();
		paths = new ArrayList<String>();
		File file=new File(filePath);
		File[] files=file.listFiles();
		if(!filePath.equals("/")) {
		    list.add(getString(R.string.predir));
		    paths.add(file.getParent());
		}
		if(files!=null)
		{
			for(int i=0;i<files.length;i++)
			{
				if(!files[i].isHidden())
				{

					if(files[i].isDirectory())
					{
						list.add(files[i].getName()+"    >");
						paths.add(files[i].getPath());
					}
					else
					{
						String name=files[i].getName();
						if(name.contains(".bfu"))
						{
							list.add(files[i].getName());
							paths.add(files[i].getPath());	
						}
					}
					
				}
			}
		}
		//
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, 
				android.R.layout.simple_list_item_1,
				list);
		mListView.setAdapter(adapter);
	
	}

}
